package com.android.li.temperature.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.li.temperature.R;
import com.android.li.temperature.data.DataModel;
import com.android.li.temperature.data.Stopwatch;
import com.android.li.temperature.impl.IPhoneStatusObserver;
import com.android.li.temperature.service.PhoneStatusManager;
import com.android.li.temperature.service.PhoneStatusService;
import com.android.li.temperature.util.Config;
import com.android.li.temperature.util.CustomToast;
import com.android.li.temperature.util.LogUtil;
import com.android.li.temperature.util.ShareUtil;
import com.android.li.temperature.util.StringUtil;
import com.android.li.temperature.util.WeakHandler;
import com.android.li.temperature.view.TimeCountView;

public class MainActivity extends Activity implements OnClickListener, IPhoneStatusObserver {

    public static final int MSG_UPDATE_UI = 0;
    public static final int MSG_STOP = 1;

    private int mPeriod;
    public static boolean isRunning = false;

    private PhoneStatusManager mPhoneStatusManager;

    private TextView tv_info;
    private TextView tv_result;
    private Button btn_start;
    private EditText et_settings;
    private TimeCountView mTime;

    private Handler mHandler = new PhoneDataHandler(this);

    private static class PhoneDataHandler extends WeakHandler<MainActivity> {
        public PhoneDataHandler(MainActivity owner) {
            super(owner);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = getOwner();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
            case MSG_UPDATE_UI:
                activity.tv_result.setText((String) msg.obj);
                //activity.mTime.updateResult((List<String>) msg.obj);
                break;
            case MSG_STOP:
                break;
            default:
                break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initValue();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        tv_info = (TextView) findViewById(R.id.tv_info);
        btn_start = (Button) findViewById(R.id.btn_start);
        tv_result = (TextView) findViewById(R.id.tv_result);
        mTime = (TimeCountView) findViewById(R.id.timeView);
        et_settings = (EditText) findViewById(R.id.et_settings);
    }

    /**
     * 初始化参数
     */
    private void initValue() {
        tv_info.setText(String.format("%s %s \n%s \n%s", getString(R.string.app_info), LogUtil.FILE_PATH, LogUtil.FILE_NAME_LOG, LogUtil.FILE_NAME_TYPE));
        mPhoneStatusManager = PhoneStatusManager.getInstance(this);
        mPhoneStatusManager.setIPhoneStatusObserver(this);
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        btn_start.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btn_start:
            if (btn_start.getText().equals(getString(R.string.btn_start_title))) {
                if (isOkInput(et_settings.getText().toString().trim())) {
                    startMonitor();
                    doStartTime();
                    isRunning = true;
                } else {
                    CustomToast.showToast(getApplicationContext(), R.string.toast_float_tip, Toast.LENGTH_LONG);
                }
            } else if (btn_start.getText().equals(getString(R.string.btn_stop_title))) {
                isRunning = false;
                stopMonitor();
                doStopTime();
            }

            updateUI();
            break;
        default:
            break;
        }
    }

    /**
     * 启动监听服务
     */
    private void startMonitor() {
        Intent intent = new Intent(this, PhoneStatusService.class);
        intent.setAction(PhoneStatusService.ACTION_START_MONITOR);
        startService(intent);
    }

    /**
     * 停止监听服务
     */
    private void stopMonitor() {
        Intent intent = new Intent(this, PhoneStatusService.class);
        intent.setAction(PhoneStatusService.ACTION_STOP_MONITOR);
        startService(intent);
    }

    private void updateUI() {
        if (isRunning) {
            btn_start.setText(R.string.btn_stop_title);
            et_settings.setEnabled(false);
        } else {
            btn_start.setText(R.string.btn_start_title);
            et_settings.setEnabled(true);
        }

        et_settings.setText(String.valueOf(getPeriod()));
    }

    private void doStartTime() {
        DataModel.getDataModel().startStopwatch();
        startUpdatingTime();
        mTime.update();
    }

    private void doStopTime() {
        DataModel.getDataModel().resetStopwatch();
        stopUpdatingTime();
    }

    private void startUpdatingTime() {
        stopUpdatingTime();
        mTime.post(mTimeUpdateRunnable);
    }

    private void stopUpdatingTime() {
        mTime.removeCallbacks(mTimeUpdateRunnable);
    }

    private Stopwatch getStopwatch() {
        return DataModel.getDataModel().getStopwatch();
    }

    private final Runnable mTimeUpdateRunnable = new TimeUpdateRunnable();

    private final class TimeUpdateRunnable implements Runnable {
        @Override
        public void run() {
            if (getStopwatch().isRunning()) {
                Log.d("sufadi", "mTimeUpdateRunnable");
                mTime.postDelayed(this, (mPeriod-1));
                if (null != mPhoneStatusManager) {
                    mPhoneStatusManager.updateMonitor();
                }
            }
        }
    }

    private boolean isOkInput(String value) {

        if (value == null) {
            return false;
        }

        if (value != null && value.equals("")) {
            return false;
        }

        if (!StringUtil.isNumeric(value)) {
            return false;
        }

        mPeriod = Integer.parseInt(value);

        setPeriod(mPeriod);

        return true;
    }

    private void setPeriod(int value) {
        ShareUtil mShareUtil = new ShareUtil(this);
        mShareUtil.setShare(Config.KEY_PERIOD, value);
    }

    private int getPeriod() {
        return new ShareUtil(this).getInt(Config.KEY_PERIOD, Config.DAFAULT_PERIOD);
    }

    @Override
    public void updateData(String result) {
        Message msg = new Message();
        msg.what = MSG_UPDATE_UI;
        msg.obj = result;
        mHandler.sendMessage(msg);
    }
    
}
